import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import Core from '@alicloud/pop-core';
import { aliyunConfig } from 'src/config/aliyun.config';
import { InjectModel } from '@nestjs/mongoose';
import { Video, VideoDocument } from 'src/mongoScheme/video.schema';
import { Model } from 'mongoose';
import { Comment, CommentDocument } from 'src/mongoScheme/comment.schema';
import { UserService } from 'src/user/user.service';
import { Like, LikeDocument } from 'src/mongoScheme/like.schema';
import { CacheService } from 'src/cache/cache.service';
@Injectable()
export class VideoService {

    constructor(
        private readonly userService:UserService,
        private readonly cacheService:CacheService,
        @InjectModel(Video.name) private videoModel: Model<VideoDocument>,
        @InjectModel(Comment.name) private commentModel: Model<CommentDocument>,
        @InjectModel(Like.name) private likeModel:Model<LikeDocument>
    ) {}

    private initVodClient() {
        var client = new Core({//填入AccessKey信息
            accessKeyId: aliyunConfig.accessKeyId,
            accessKeySecret: aliyunConfig.accessKeySecret,
            endpoint: aliyunConfig.endpoint,
            apiVersion: '2017-03-21'
        });

        return client;
    }
    //获取vod阿里云视频凭证
    async getvod(Title: string, FileName: string) {
        const Client = await this.initVodClient()
        const vodback = await Client.request("CreateUploadVideo", {
            Title,
            FileName
        }, {})
        return { vod: vodback }
    }

    //上传视频

    async uploadvideo(vodid: string, userid: string, title: string) {
        const model = new this.videoModel({ vodid, title, userid })
        const db = await model.save()
        return db
    }

    //获取视频列表

    async videoList(page: number, pagesize: number) {
        const skip = (page - 1) * pagesize
        let dbback = await this.videoModel.find().skip(skip).limit(pagesize).populate('userid', 'nickname avater')

        const total = await this.videoModel.countDocuments()
        return { list: dbback, total }
    }

    //获取视频详情 +1
    async videodetail(videoid:string){
        const dbback = await this.videoModel.findById(videoid)
        console.log('获取视频详情')
        await this.cacheService.setScore(videoid,1)
        return dbback
    }

    //视频评论 +3

    async comment(video:string,user:string,content:string){
        const {comments} = await this.videodetail(video)
        await this.videoModel.findByIdAndUpdate(video,{comments:comments+1})
        const model = new this.commentModel({video,user,content})
        await model.save()
        await this.cacheService.setScore(video,3)
        return '评论成功'
    }

    //删除视频评论 -1

    async delcomment(commentid:string,user_id:string){
        const {video,user} = await this.commentModel.findById(commentid)
        const {comments} = await this.videodetail(video.toString())
        console.log(user , user.toString() )
        if(user_id !== user.toString() ){
            throw new HttpException('该评论无法删除',HttpStatus.BAD_REQUEST)
        }else{
            await this.commentModel.findByIdAndDelete(commentid)
            await this.videoModel.findByIdAndUpdate(video,{comments:comments-1})
            await this.cacheService.setScore(video.toString(),-1)
            return '删除评论成功'
        }
    }
    //获取评论列表
    async commentList(page: number, pagesize: number,videoid:string) {
        const skip = (page - 1) * pagesize
        let dbback = await this.commentModel.find({video:videoid}).skip(skip).limit(pagesize).populate('user', 'nickname avater')

        const total = await this.commentModel.countDocuments({video:videoid})
        return { list: dbback, total }
    }

    //喜欢视频 +4
    async likevideo(video:string,user:string){
        const likedetail =await this.likeModel.findOne({video,user})
        if(likedetail){
            const {like,dislike} = likedetail
            if(like === 1 && dislike === 0){
                throw new HttpException('已设置喜欢',HttpStatus.BAD_REQUEST)
            }else if(like === 0 && dislike === 1){
                await this.likeModel.findOneAndUpdate({video},{like:1,dislike:0})
                const {like} = await this.videoModel.findById(video)
                await this.videoModel.findByIdAndUpdate(video,{like:like + 1})
                await this.cacheService.setScore(video,4)
                return '点赞成功'
            }
        }else{
            const model = new this.likeModel({video,user,like:1,dislike:0})
            await model.save()
            const {like} = await this.videoModel.findById(video)
            await this.videoModel.findByIdAndUpdate(video,{like:like + 1})
            await this.cacheService.setScore(video,4)
            return '点赞成功'
        }
        
    }
    //取消喜欢 -2
    async dislikevideo(video:string,user:string){
        const likedetail =await this.likeModel.findOne({video,user})
        if(likedetail){
            const {like,dislike} = likedetail
            if(like === 0 && dislike === 1){
                throw new HttpException('已设置不喜欢',HttpStatus.BAD_REQUEST)
            }else if(like === 1 && dislike === 0){
                await this.likeModel.findOneAndUpdate({video},{like:0,dislike:1})
                const {dislike} = await this.videoModel.findById(video)
                await this.videoModel.findByIdAndUpdate(video,{like:dislike + 1})
                await this.cacheService.setScore(video,-2)
                return '设置不喜欢成功'
            }
        }else{
            const model = new this.likeModel({video,user,like:0,dislike:1})
            await model.save()
            const {dislike} = await this.videoModel.findById(video)
            await this.videoModel.findByIdAndUpdate(video,{dislike:dislike + 1})
            await this.cacheService.setScore(video,-2)
            return '设置不喜欢成功'
        }
        
    }
    //获取喜欢列表
    async likeList(page: number, pagesize: number,user:string) {
        const skip = (page - 1) * pagesize
        let dbback = await this.likeModel.find({user:user,like:1}).skip(skip).limit(pagesize)
        .populate('user', 'nickname avater')
        .populate('video','title vodid like dislike comments')

        const total = await this.likeModel.countDocuments({user:user,like:1})
        return { list: dbback, total }
    }

     //获取不喜欢列表
    async dislikeList(page: number, pagesize: number,user:string) {
        const skip = (page - 1) * pagesize
        let dbback = await this.likeModel.find({user:user,dislike:1}).skip(skip).limit(pagesize)
        .populate('user', 'nickname avater')
        .populate('video','title vodid like dislike comments')

        const total = await this.likeModel.countDocuments({user:user,dislike:1})
        return { list: dbback, total }
    }

    async getHoc(size:string){
        const data = await this.cacheService.getHotvideo(size)
        console.log('获取热门视频',data)
        return data
    }

}
